#!/bin/bash

export_env() {
  while IFS= read -r line || [[ -n "$line" ]]; do
    if [[ "$line" =~ ^\s*# ]] || [[ -z "$line" ]]; then
      continue # 跳过注释和空行
    fi
    
    # 提取键值对
    if [[ "$line" =~ ^([A-Z0-9_]+)=(.*)$ ]]; then
      key="${BASH_REMATCH[1]}"
      value="${BASH_REMATCH[2]}"
      # 去除值两端的引号（单引号和双引号）
      value="${value%[\"\']}"
      value="${value#[\"\']}"
      # 导出变量
      export "$key"="$value"
      echo "> export $key"
    fi
  done < .env
}

# 检查 .env 文件是否存在
if [[ ! -f .env ]]; then
  echo "Error: .env file not found in directory $(pwd)"
  echo ""
  echo "There is an .env.example project root directory, and you can template"
  echo "it to create you own .env file, and then try again. Remember that you"
  echo "should not commit your own .env file to git, and if you add new "
  echo "environment variables, you should add them to the .env.example file."
  echo ""
  exit 1
fi

export_env

echo "> Environment variables exported successfully."